package com.utils;
import com.aliyun.oss.OSSClient;
import com.pojo.OssFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;

import com.mapper.OssFileMapper;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 存放用户文件
 * 文件id,用户id,文件原名称,文件在oss名称
 * */
@Component
public class OssUtils {
    @Resource
    OssFileMapper ossFileMapper;
    public static OssUtils ossUtils;
    @PostConstruct
    public void init(){
        ossUtils=this;
        ossUtils.ossFileMapper=ossFileMapper;
    }

    public static OssFile validName(String fileName){
      List<OssFile> list=ossUtils.ossFileMapper.getByExactFile(fileName);
      return  list.size()>0?list.get(0):null;
    }



    public static OssFile uploadFile(MultipartFile multipartFile) throws IOException {
        OssFile ossFile=new OssFile();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tGL3eUPHPPE6bKWJgWc";
        String accessKeySecret = "7w2dOBySu0WBE33EOCdgHXJmwoFnug";
        String bucketName = "graduation-app";

        String fileName = multipartFile.getOriginalFilename();
        if(Objects.equals(validName(fileName), null)){
            ossFile.setFile_name(fileName);
            ossFile.setUpload_time( timeFormat.format(new Date()));
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if(!suffixName.isEmpty()){
                if(Objects.equals(suffixName, ".png") ||Objects.equals(suffixName, ".jpg")||Objects.equals(suffixName, ".jpeg"))
                    ossFile.setFile_type(0);
                else if(Objects.equals(suffixName, ".pdf")||Objects.equals(suffixName, ".docx")||Objects.equals(suffixName, ".doc")||Objects.equals(suffixName, ".xls")||Objects.equals(suffixName, ".xlsx"))
                    ossFile.setFile_type(1);
                else ossFile.setFile_type(2);
            }
            // 生成上传文件名
            String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
            ossFile.setTime_stamp(finalFileName);
            String objectName ="wqz" + "/" +  sdf.format(new Date())+ "/" + finalFileName;
            ossFile.setOss_file_name(objectName);
            // 创建临时文件
            File file = File.createTempFile("upload-", "-" + multipartFile.getOriginalFilename());
            // 转换并保存
            multipartFile.transferTo(file);
            // 处理文件...
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, file);
            // 设置URL过期时间为365天。
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000*24*365);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            ossFile.setOss_file_url(url.toString());
            ossFile.setIs_delete(Boolean.FALSE);
            ossClient.shutdown();
            // 完成后删除临时文件
            file.delete();
        }else{
            ossFile=validName(fileName);
        }
        return ossFile;
    }

}


